package cn.elwy.rcp.ui.provider;

import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

import cn.elwy.rcp.core.model.ui.tree.TreeElement;

/**
 * 内容提供者类，支持树、表格、列表等控件
 * 
 * @author huangsq
 * @version 1.0, 2014-06-23
 * @since 1.0, 2014-06-23
 */
public class DataContentProvider implements ITreeContentProvider {

  private DataParser parser;

  public DataContentProvider() {
  }

  public DataContentProvider(DataParser parser) {
    this.parser = parser;
  }

  @Override
  public Object[] getElements(Object element) {
    if (element instanceof List) {
      return ((List<?>) element).toArray();
    } else if (element instanceof Object[]) {
      return (Object[]) element;
    } else if (element instanceof TreeElement) {
      return getChildren(element);
    } else if (element instanceof Map) {
      return ((Map<?, ?>) element).values().toArray();
    } else if (element instanceof Array) {
      return ((Object[]) element);
    }
    return new Object[0];
  }

  @Override
  public void dispose() {
  }

  @Override
  public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
    System.out.println("inputChanged:" + oldInput + "," + newInput);
  }

  @Override
  public Object[] getChildren(Object element) {
    if (element instanceof List) {
      return ((List<?>) element).toArray();
    } else if (element instanceof Object[]) {
      return (Object[]) element;
    } else if (element instanceof TreeElement) {
      return ((TreeElement) element).getChildren();
    } else if (element instanceof Map) {
      return ((Map<?, ?>) element).entrySet().toArray();
    } else if (element instanceof Array) {
      return ((Object[]) element);
    } else if (parser != null) {
      return parser.getChildren(element);
    }
    return null;
  }

  @Override
  public Object getParent(Object element) {
    if (element instanceof TreeElement) {
      return ((TreeElement) element).getParent();
    } else {
      return null;
    }
  }

  @Override
  public boolean hasChildren(Object element) {
    if (element instanceof TreeElement) {
      TreeElement item = (TreeElement) element;
      if (item.isDynamic()) {
        return true;
      } else {
        return item.hasChildren();
      }
    } else {
      Object[] childrent = getChildren(element);
      return childrent != null && childrent.length > 1;
    }
  }

  public void setParser(DataParser parser) {
    this.parser = parser;
  }

  public DataParser getParser() {
    return parser;
  }

}